﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using cash_desk_model;
using cash_desk_model.src.model;
using cash_desk_model.src.security;
using System.Collections;

namespace cash_desk
{
    public partial class CashierForm : Form
    {
        public static string CurrentUser;
        private LoginForm _parent;
        private cash_desk_model.src.security.User _authentificatedUser;
        private static int RedRowsCount = 0;

        public CashierForm(LoginForm parent, cash_desk_model.src.security.User authentificatedUser)
        {
            this._parent = parent;
            this._authentificatedUser = authentificatedUser;
            InitializeComponent();
            this.userNameLabel.Text = this.userNameLabel.Text + authentificatedUser.FullName;
            CurrentUser = authentificatedUser.UserName;
            this.payTypeComboBox.SelectedIndex = 0;

            productsTable.Columns["Quantity"].ValueType= typeof(Int32);
            //disable transaction button before grid is empty
            completeTransactionButton.Enabled = false;
            amountTextBox.Enabled = false;
        }

        //private void productEdditor_Click(object sender, EventArgs e)
        //{
        //    CashDeskService service = new CashDeskService();
        //    CashDeskService.SetupDBConn();
        //    Product product = service.GetProduct(this.codeTextBox.Text);
        //    if (product != null && this.QuantityTextBox.Text.Length > 0)
        //    {
        //        Double totalAmount = product.Price * Double.Parse(this.QuantityTextBox.Text);
        //        this.productsTable.Rows.Add(this.codeTextBox.Text, this.QuantityTextBox.Text, product.ProductName, product.Type, totalAmount, product.Description, product.Provider);
        //        Double debt = Double.Parse(this.debtTextBxo.Text) + totalAmount;
        //        this.debtTextBxo.Text = debt.ToString();
        //    }
        //    CashDeskService.DestroyDBConn();
        //}

        //private void clearButton_Click(object sender, EventArgs e)
        //{
        //    this.codeTextBox.Text = "";
        //    this.QuantityTextBox.Text = "";
        //    this.productsTable.Rows.Clear();
        //    this.payTypeComboBox.SelectedItem = 0;
        //    this.debtTextBxo.Text = "0.00";
        //    this.amountTextBox.Text = "";
        //}

        private void logoutButton_Click(object sender, EventArgs e)
        {
            Hide();
        }

        private void CasherForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            Application.Exit();
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void closeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Hide();
        }

        private void changePasswordToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ChangePasswordForm passwordChangeDialog = new ChangePasswordForm(CurrentUser);
            passwordChangeDialog.ShowDialog();
        }

        private void completeTransactionButton_Click(object sender, EventArgs e)
        {
            if ("ნაღდი ფული".Equals(this.payTypeComboBox.SelectedItem.ToString()) && Double.Parse(this.debtTextBxo.Text) > 0
                && Double.Parse(this.debtTextBxo.Text) <= Double.Parse(this.amountTextBox.Text))
            {
                cash_desk_model.CashDeskService service = new CashDeskService();
                cash_desk_model.CashDeskService.SetupDBConn();

                long paymentId = service.SavePayment(DateTime.Now, this.payTypeComboBox.SelectedItem.ToString(), Double.Parse(
                    this.debtTextBxo.Text), "", this._authentificatedUser.UserName);

                DataGridViewRowCollection rows = this.productsTable.Rows;

                //const int indexOfProductCodeColumn = 0;
                //const int indexOfProductQunatityColumn = 5;
                //const int indexOfProductPriceColumn = 3;

                foreach (DataGridViewRow row in rows)
                {
                    if (row.Cells["Quantity"].Value != null)
                    {
                        //service.UpdateProductQuantity(row.Cells[indexOfProductCodeColumn].Value.ToString(),
                        //    Double.Parse(row.Cells[indexOfProductQunatityColumn].Value.ToString()));
                        //service.SaveSoldProduct(paymentId, row.Cells[indexOfProductCodeColumn].Value.ToString(),
                        //    Double.Parse(row.Cells[indexOfProductPriceColumn].Value.ToString()),
                        //    Double.Parse(row.Cells[indexOfProductQunatityColumn].Value.ToString()));
                        service.UpdateProductQuantity(row.Cells["Code"].Value.ToString(),
                            Double.Parse(row.Cells["Quantity"].Value.ToString()));
                        service.SaveSoldProduct(paymentId, row.Cells["Code"].Value.ToString(),
                            Double.Parse(row.Cells["ProductPrice"].Value.ToString()),
                            Double.Parse(row.Cells["Quantity"].Value.ToString()));
                    }
                }

                cash_desk_model.CashDeskService.DestroyDBConn();

                MessageBox.Show("გადახდა განხორციელდა წარმატებით");
            }
            else
            {
                if ("ბარათი".Equals(this.payTypeComboBox.SelectedItem.ToString()) && Double.Parse(this.debtTextBxo.Text) > 0)
                {
                    cash_desk_model.CashDeskService service = new CashDeskService();
                    cash_desk_model.CashDeskService.SetupDBConn();

                    service.SavePayment(DateTime.Now, this.payTypeComboBox.SelectedItem.ToString(), Double.Parse(
                        this.debtTextBxo.Text), "", this._authentificatedUser.UserName);

                    cash_desk_model.CashDeskService.DestroyDBConn();

                    MessageBox.Show("გადახდა განხორციელდა წარმატებით");
                }
                else
                {
                    if (Double.Parse(this.debtTextBxo.Text) <= 0)
                    {
                        MessageBox.Show("პროდუქტი არ არის მაორჩეული");
                    }
                    
                    if("ნაღდი ფული".Equals(this.payTypeComboBox.SelectedItem.ToString()) 
                        && Double.Parse(this.debtTextBxo.Text) > Double.Parse(this.amountTextBox.Text))
                    {
                        MessageBox.Show("არასაკმარისი თანხა");
                    }
                }
            }
        }

        private void payTypeComboBox_SelectedIndexChanged(object sender, EventArgs e)
        { 
            if ("ნაღდი ფული".Equals(this.payTypeComboBox.SelectedItem.ToString()))
            {
                this.amountTextBox.Enabled = true;                          
            }
            if ("ბარათი".Equals(this.payTypeComboBox.SelectedItem.ToString()))
            {
                this.amountTextBox.Enabled = false;
            }
        }

        private void productsTable_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0)
            {
                //check if productCode is entered
                if (productsTable.Rows[e.RowIndex].Cells["Code"].Value != null)
                {
                    //if quantity is not provided set it to 1
                    if (string.IsNullOrEmpty(productsTable.Rows[e.RowIndex].Cells["Quantity"].FormattedValue.ToString()))
                    {
                        productsTable.Rows[e.RowIndex].Cells["Quantity"].Value = 1;
                    }

                    //productsTable.Rows[e.RowIndex].Cells["Quantity"].Value = Math.Abs(Convert.ToInt32(productsTable.Rows[e.RowIndex].Cells["Quantity"].Value));

                    //start filling the row
                    CashDeskService service = new CashDeskService();
                    CashDeskService.SetupDBConn();
                    Product product = service.GetProduct(productsTable.Rows[e.RowIndex].Cells["Code"].Value.ToString());

                    //if product exists fill row with corresponding info
                    if (product != null)
                    {
                        //if Cell is empty previuous price is 0, else Current value
                        Double PreviousPrice = (string.IsNullOrEmpty(productsTable.Rows[e.RowIndex].Cells["ProductPrice"].FormattedValue.ToString())) ? 0 : Convert.ToDouble(productsTable.Rows[e.RowIndex].Cells["ProductPrice"].Value);
                        Double TotalPrice = product.Price * Convert.ToInt32(productsTable.Rows[e.RowIndex].Cells["Quantity"].Value);

                        productsTable.Rows[e.RowIndex].Cells["ProductName"].Value = product.ProductName;
                        productsTable.Rows[e.RowIndex].Cells["PricePerUnit"].Value = product.Price;
                        productsTable.Rows[e.RowIndex].Cells["ProductType"].Value = product.Type;
                        productsTable.Rows[e.RowIndex].Cells["Provider"].Value = product.Provider;
                        productsTable.Rows[e.RowIndex].Cells["ProductPrice"].Value = TotalPrice;
                        productsTable.Rows[e.RowIndex].Cells["Description"].Value = product.Description;
                        //productsTable.Rows[e.RowIndex].Cells["ProductName"].Style.ForeColor = Color.Black;
                        productsTable.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.White;
                        productsTable.Rows[e.RowIndex].Cells["ProductName"].Style.Font = new Font(productsTable.Rows[e.RowIndex].Cells["ProductName"].InheritedStyle.Font, FontStyle.Regular);

                        //              current Total Amout    + Current Row product price     - current row product price before editing
                        debtTextBxo.Text = (Convert.ToDouble(debtTextBxo.Text) + TotalPrice - PreviousPrice).ToString();

                        //if product exists allow users to add rows
                        if (productsTable.AllowUserToAddRows == false)
                            productsTable.AllowUserToAddRows = true;
                        if (amountTextBox.Enabled == false)
                            amountTextBox.Enabled = true;
                    }

                    // if product doesn't exist "raiseError" and disable adding new rows
                    else
                    {
                        if (productsTable.Rows[e.RowIndex].DefaultCellStyle.BackColor != Color.Red)
                        {
                            productsTable.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Red;
                            RedRowsCount++;
                        }
                        productsTable.Rows[e.RowIndex].Cells["ProductName"].Value = "ასეთი პროდუქტი არ მოიძებნა";
                        productsTable.Rows[e.RowIndex].Cells["ProductName"].Style.Font = new Font(productsTable.Rows[e.RowIndex].Cells["ProductName"].InheritedStyle.Font, FontStyle.Bold);
                        //productsTable.Rows[e.RowIndex].Cells["ProductName"].Style.ForeColor = Color.Red;
                        productsTable.Rows[e.RowIndex].Cells["ProductType"].Value = "";
                        productsTable.Rows[e.RowIndex].Cells["Provider"].Value = "";
                        productsTable.Rows[e.RowIndex].Cells["ProductPrice"].Value = "";
                        productsTable.Rows[e.RowIndex].Cells["Description"].Value = "";
                        productsTable.Rows[e.RowIndex].Cells["Quantity"].Value = "";
                        productsTable.Rows[e.RowIndex].Cells["PricePerUnit"].Value = "";

                        //disable new rows and Complete button
                        productsTable.AllowUserToAddRows = false;
                        amountTextBox.Enabled = false;
                    }
                    CashDeskService.DestroyDBConn();
                }
                else
                //case if code is deleted.. demand it!
                {
                    if (productsTable.Rows[e.RowIndex].DefaultCellStyle.BackColor != Color.Red)
                    {
                        productsTable.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Red;
                        RedRowsCount++;
                    }
                    productsTable.Rows[e.RowIndex].Cells["ProductName"].Value = "საჭიროა კოდი";
                    productsTable.Rows[e.RowIndex].Cells["ProductName"].Style.Font = new Font(productsTable.Rows[e.RowIndex].Cells["ProductName"].InheritedStyle.Font, FontStyle.Bold);
                    //productsTable.Rows[e.RowIndex].Cells["ProductName"].Style.ForeColor = Color.Red;
                    productsTable.Rows[e.RowIndex].Cells["ProductType"].Value = "";
                    productsTable.Rows[e.RowIndex].Cells["Provider"].Value = "";
                    productsTable.Rows[e.RowIndex].Cells["ProductPrice"].Value = "";
                    productsTable.Rows[e.RowIndex].Cells["Description"].Value = "";
                    productsTable.Rows[e.RowIndex].Cells["Quantity"].Value = "";
                    productsTable.Rows[e.RowIndex].Cells["PricePerUnit"].Value = "";


                    //disable new rows and Complete button
                    productsTable.AllowUserToAddRows = false;
                    amountTextBox.Enabled = false;
                }
            }
        }

        //allow insert in Quantity Column only digits
        private void productsTable_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            if (productsTable.Columns[productsTable.CurrentCell.ColumnIndex].Name.Equals("Quantity"))
                e.Control.KeyPress += new KeyPressEventHandler(Control_KeyPress);
        }
        //if current column is quantity filter keys
        void Control_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!Char.IsNumber(e.KeyChar) && e.KeyChar != (Char)Keys.Back)
            {
                e.Handled = true;
            }
            else
            {
                e.Handled = false;
            }
            //throw new NotImplementedException();
        }

        private void productsTable_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyValue == (int)Keys.Delete && (productsTable.Rows.Count != 1 || productsTable.AllowUserToAddRows == false))
            {
                //if it's not error row then remove from total amount current row product price value
                if (productsTable.CurrentRow.DefaultCellStyle.BackColor != Color.Red)
                {
                    debtTextBxo.Text = (Convert.ToDouble(debtTextBxo.Text) - Convert.ToDouble(productsTable.CurrentRow.Cells["ProductPrice"].Value)).ToString();
                }
                else
                //if red row is removed decrement RedRowsCount
                {
                    RedRowsCount--;
                }
                //if (productsTable.Rows.Count != 1 || productsTable.AllowUserToAddRows==false)
                if (productsTable.AllowUserToAddRows == false)
                {
                    productsTable.Rows.Remove(productsTable.CurrentRow);
                }
                else
                {
                    if (productsTable.CurrentRow.Index != productsTable.NewRowIndex)
                        productsTable.Rows.Remove(productsTable.CurrentRow);
                }
                if (RedRowsCount == 0)
                {
                    productsTable.AllowUserToAddRows = true;
                    amountTextBox.Enabled = true;
                }
            }
        }

        private void amountTextBox_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!Char.IsNumber(e.KeyChar) && e.KeyChar != (Char)Keys.Back && e.KeyChar!=(Char)Keys.Delete)
            {
                e.Handled = true;
            }
            else
            {
                e.Handled = false;
            }
        }

        private void productsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ProductsForm productsForm = new ProductsForm();
            productsForm.Show();
        }

        private void amountTextBox_Validated(object sender, EventArgs e)
        {
            if (amountTextBox.Text.Length > 0)
            {
                if (Convert.ToDouble(amountTextBox.Text) >= Convert.ToDouble(debtTextBxo.Text))
                {
                    completeTransactionButton.Enabled = true;
                    changeBox.Text = (Convert.ToDouble(amountTextBox.Text) - Convert.ToDouble(debtTextBxo.Text)).ToString();
                }
                else
                {
                    completeTransactionButton.Enabled = false;
                    changeBox.Clear();
                }
            }
        }

        private void transactionsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            TransactionsForm transactionsForm = new TransactionsForm();
            transactionsForm.Show();
        }

        private void registrationToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AddOrDeleteUserForm addNewUserForm = new AddOrDeleteUserForm();
            addNewUserForm.Show();
        }
    }
}
